package org.iks.common;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.iks.common.exception.BusinessException;

import java.io.Serializable;
import java.util.Objects;

/**
 * @author kzou
 */
@Slf4j
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AjaxResult<T> implements Serializable {

    /**
     * 消息说明
     */
    private String message;

    /**
     * 消息状态码
     */
    private int code;

    /**
     * 消息体
     */
    private T data;

    public boolean isSuccess() {
        return Objects.equals(this.code, ResultCode.SUCCESS.getCode());
    }

    public AjaxResult(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <T> AjaxResult<T> success(T data) {
        return new AjaxResult<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
    }
    public static <T> AjaxResult<T> success() {
        return new AjaxResult<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), null);
    }

    public static <T> AjaxResult<T> error(String message) {
        return AjaxResult.error(ResultCode.ERROR.getCode(), message);
    }

    public static <T> AjaxResult<T> error(BusinessException exception) {
        return AjaxResult.error(exception.getErrorCode(), exception.getErrorMessage());
    }

    public static <T> AjaxResult<T> error(Integer code, String message) {
        return new AjaxResult<>(code, message, null);
    }

    public static <T> AjaxResult<T> error(ResultCode result) {
        return AjaxResult.error(result.getCode(), result.getMessage());
    }

    public T data() {
        if (isSuccess()) {
            return data;
        }
        log.info("rpc response error {}", this);
        throw new BusinessException(ResultCode.RPC_EXCEPTION);
    }

}
